#include "ParserWindow.h"
#include <QFileDialog>
#include <QMessageBox>

namespace LightChart {
ParserWindow::ParserWindow(QWidget *parent) : QDialog(parent), okToContinue(false)
{
    storage = &Storage::get_instance();
    setupUi(this);
    labelWarning->hide();
    setupConnections();
}
void ParserWindow::setupConnections()
{
    connect(buttonBrowse, SIGNAL(clicked()), this, SLOT(browse()));
    connect(lineEditInputFile, SIGNAL(textChanged(QString)), this, SLOT(onFileChange()));
    connect(buttonLoad,SIGNAL(clicked()),this,SLOT(onButtonLoadClick()));
    connect(buttonFinish,SIGNAL(clicked()),this,SLOT(onButtonFinishClick()));
}
void ParserWindow::browse()
{
    QString file = "";
    file = QFileDialog::getOpenFileName(this,tr("Open file"),QString("."), tr("Plain text files (*.txt *.inp *.dat)"));
    if(!file.isEmpty())
        lineEditInputFile->setText(file);
}
void ParserWindow::onFileChange()
{
    lineEditInputFile->text().isEmpty() ? buttonLoad->setEnabled(false) : buttonLoad->setEnabled(true);
}
void ParserWindow::onButtonLoadClick()
{
    bool header = false, footer = false, labels = false;
    SeriesOrientation orientation;
    if(radioData->isChecked())
    {
        header = false;
        footer = false;
    }
    else if(radioHeader->isChecked())
    {
        header = true;
        footer = false;
    }
    else if(radioHF->isChecked())
    {
        header = true;
        footer = true;
    }
    else if(radioFooter->isChecked())
    {
        header = false;
        footer = true;
    }
    if(radioVertical->isChecked())
    {
        orientation = VERTICAL_SERIES;
    }
    else
    {
        orientation = HORIZONTAL_SERIES;
    }
    checkBoxLabels->isChecked() ? labels = true : labels = false;
    if( (okToContinue = parser.parse(storage, lineEditInputFile->text().toStdString().c_str(),orientation,header,footer,labels)) )
    {
        QMessageBox::information(this,tr("Parsing info"),tr("Parsing has finished succesfully. You can now continue or parse another file."));
        buttonFinish->setEnabled(true);
        lineEditInputFile->setText("");
    }
    else
    {
        QMessageBox::warning(this,"File error","Cannot open / read specified file.");
    }
}

void ParserWindow::onButtonFinishClick()
{
    if(okToContinue)
    {
        hide();
        reset();
        emit onFinishClicked();
    }
}
void ParserWindow::reset()
{
    lineEditInputFile->setText("");
    checkBoxLabels->setChecked(false);
    radioData->setChecked(true);
    radioVertical->setChecked(true);
    labelWarning->hide();
    buttonLoad->setEnabled(false);
    buttonFinish->setEnabled(false);
}
}
